<template>
  <div class="report-box">
    <h2>📊 成绩报表</h2>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { ECharts, EChartsOption } from 'echarts'
import useScoreStore from '@/store/modules/score'

let scoreStore = useScoreStore()

// DOM ref & chart instance
const chartRef = ref<HTMLDivElement | null>(null)
let chart: ECharts | null = null

// 示例响应式数据（真实项目通常来自 props 或 API）

const categories: string[] = []
const math: number[] = []
const chinese: number[] = []
const english: number[] = []

// 先按学生分组
scoreStore.tableData.reduce((acc: any, cur) => {
  if (!acc[cur.name]) {
    acc[cur.name] = { chinese: null, math: null, english: null }
    categories.push(cur.name)
  }
  if (cur.course === '语文') acc[cur.name].chinese = Number(cur.score)
  if (cur.course === '数学') acc[cur.name].math = Number(cur.score)
  if (cur.course === '英语') acc[cur.name].english = Number(cur.score)
  return acc
}, {})

// 转换成 echarts 需要的数组
categories.forEach((name) => {
  const stu = scoreStore.tableData.find((s) => s.name === name) // 找学生存在
  if (stu) {
    const record = scoreStore.tableData.filter((s) => s.name === name)
    math.push(Number(record.find((r) => r.course === '数学')?.score ?? 0))
    chinese.push(Number(record.find((r) => r.course === '语文')?.score ?? 0))
    english.push(Number(record.find((r) => r.course === '英语')?.score ?? 0))
  }
})

const data = {
  categories,
  math,
  chinese,
  english,
}

// 防抖函数（简单实现）
function debounce<T extends (...args: any[]) => void>(fn: T, wait = 100) {
  let timer: number | undefined
  return (...args: Parameters<T>) => {
    if (timer) window.clearTimeout(timer)
    timer = window.setTimeout(() => fn(...args), wait)
  }
}

const initChart = () => {
  if (!chartRef.value) return
  chart = echarts.init(chartRef.value)

  const option: EChartsOption = {
    title: { text: '学生成绩统计', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['数学', '语文', '英语'], top: '10%' },
    xAxis: { type: 'category', data: data.categories },
    yAxis: { type: 'value' },
    series: [
      { name: '数学', type: 'bar', data: data.math },
      { name: '语文', type: 'bar', data: data.chinese },
      { name: '英语', type: 'line', data: data.english, smooth: true },
    ],
  }

  chart.setOption(option)
  chart.on('click', (params) => {
    // 示例：点击事件
    console.log('clicked', params)
  })
}

const handleResize = debounce(() => chart?.resize(), 120)

onMounted(async () => {
  // 等 DOM 真正渲染完
  await nextTick()
  initChart()
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
  chart = null
})

// 当 data 变更时只更新必要部分（高效）
watch(
  data,
  (newVal) => {
    if (!chart) return
    chart.setOption({
      xAxis: { data: newVal.categories },
      series: [
        { name: '数学', data: newVal.math },
        { name: '语文', data: newVal.chinese },
        { name: '英语', data: newVal.english },
      ],
    })
  },
  { deep: true },
)
</script>

<style scoped>
.chart {
  width: 100%;
  height: 400px; /* 一定要有高度，否则不显示 */
}
</style>
